<?php
namespace app\index\controller;

class Sms extends Common
{
	//短信页面
    public function index()
    {    	

        return $this->fetch();
    }

    //发送短信
    public function send_sms()
    {

        $mobile_string = input('mobile_string');
        $content = input('content');
        $send_time = input('send_time');

        // 统计字节长度
        $stringLen = mb_strlen($content,'utf-8');
        $reduceNum = 1;
        if($stringLen > 70){
            $reduceNum = ceil($stringLen / 67);
        }

        
        $mobile_array = explode(",",$mobile_string);
        $mobile_count = count($mobile_array);   

        if($mobile_count == 0)$this->error('请输入手机号码!');

        $billing = db('billing')->select();

        //计算短信费用
        foreach ($billing as $key => $value) {
            if($value['number'] > $mobile_count){
                $is_bool_price=$value['price'];
                break; 
            }
        }

        //每条价格
        if(isset($is_bool_price)){
            $sms_price = $is_bool_price;
        }else{
            $billing_price = array_column($billing, 'price');
            $sms_price = min($billing_price);
        }
        $sms_price = $sms_price * $reduceNum;

        //总费用
        $total_price = $mobile_count*$sms_price;

        if($total_price > $this->amount)$this->error('费用不足');

        // 发送短信
        $res = sendSMS($mobile_string,$content,$send_time);
        if($res['returnstatus'] == 'Faild'){
            $this->error($res['message']);
        }

        //号码库入库
        $mobile_lib_select = db('mobile_lib')->where(['uid'=>$this->info['id'],'mobile'=>['in',$mobile_array]])->select();
        $mobile_lib_mobile = array_column($mobile_lib_select, 'mobile');
        $mobile_lib_insert = $mobile_array;

        //去除已入库的电话
        if(!empty($mobile_lib_mobile)){
            foreach ($mobile_lib_mobile as $key => $value) {
                $key = array_search($value,$mobile_lib_insert);
                unset($mobile_lib_insert[$key]);
            }
        }
        
        if(!empty($mobile_lib_insert)){
            foreach ($mobile_lib_insert as $key => $value) {
                $data['uid'] = $this->info['id'];
                $data['mobile'] = $value;
                $result = $this->match($value);
                $data['mobile_type'] = $result['type'];
                $insert_data[] = $data;
            }
            db('mobile_lib')->insertAll($insert_data);
        }
        
        if(empty($send_time)){
            //钱包减少
            db('member')->where(['id'=>$this->info['id']])->setDec('amount',$total_price);

            $member_flow_array['sms_price'] = $sms_price;
            $member_flow_array['moble_count'] = $mobile_count;
            $member_flow_data['text_content'] = json_encode($member_flow_array);
            $member_flow_data['type'] = '-1';
            $member_flow_data['time'] = time();
            $member_flow_data['money'] = $total_price;
            $member_flow_data['uid'] = $this->info['id'];

            //流水入
            db('member_flow')->insert($member_flow_data);

            $sms_send_data['send_time'] = time();
            $sms_send_data['status'] = '1';
        }else{
            $sms_send_data['status'] = '0';
            $sms_send_data['send_time'] = strtotime($send_time);
        }

        //发送短信记录
        $sms_send_data['content'] = $content;
        $sms_send_data['mobile_lib'] = json_encode($mobile_array);
        $sms_send_data['sms_cost'] = $total_price;
        $sms_send_data['sms_count'] = $mobile_count;
        $sms_send_data['creatime'] = time();
        $sms_send_data['uid'] = $this->info['id'];

        db('sms_send')->insert($sms_send_data);
        $this->success('添加成功!');
    }

    //循环短信
    public function send_cycle_sms(){
        $mobile_string = input('mobile_string');
        $content = input('content');
        $startTime = input('startTime');
        $endTime = input('endTime');

        //cyctype
        $cyctype = input('cyctype');

        //时间
        $month = input('month');
        $day = input('day');
        $hour = input('hour');
        $minute = input('minute');
        $week = input('week');

        $mobile_array = explode(",",$mobile_string);
        $mobile_count = count($mobile_array);   

        if($mobile_count == 0)$this->error('请输入手机号码!');

        $billing = db('billing')->select();

        //计算短信费用
        foreach ($billing as $key => $value) {
            if($value['number'] > $mobile_count){
                $is_bool_price=$value['price'];
                break; 
            }
        }

        //每条价格
        if(isset($is_bool_price)){
            $sms_price = $is_bool_price;
        }else{
            $billing_price = array_column($billing, 'price');
            $sms_price = min($billing_price);
        }

        //总费用
        $total_price = $mobile_count*$sms_price;

        if($total_price > $this->amount)$this->error('费用不足');

        //号码库入库
        $mobile_lib_select = db('mobile_lib')->where(['uid'=>$this->info['id'],'mobile'=>['in',$mobile_array]])->select();
        $mobile_lib_mobile = array_column($mobile_lib_select, 'mobile');
        $mobile_lib_insert = $mobile_array;

        //去除已入库的电话
        if(!empty($mobile_lib_mobile)){
            foreach ($mobile_lib_mobile as $key => $value) {
                $key = array_search($value,$mobile_lib_insert);
                unset($mobile_lib_insert[$key]);
            }
        }
        
        if(!empty($mobile_lib_insert)){
            foreach ($mobile_lib_insert as $key => $value) {
                $data['uid'] = $this->info['id'];
                $data['mobile'] = $value;
                $result = $this->match($value);
                $data['mobile_type'] = $result['type'];
                $insert_data[] = $data;
            }
            db('mobile_lib')->insertAll($insert_data);
        }

        $sms_send_data['status'] = '0';

        //发送短信记录
        $sms_send_data['content'] = $content;
        $sms_send_data['mobile_lib'] = json_encode($mobile_array);
        $sms_send_data['creatime'] = time();
        $sms_send_data['send_start_time'] = strtotime($startTime);
        $sms_send_data['send_end_time'] = strtotime($endTime);
        $sms_send_data['uid'] = $this->info['id'];
        $sms_send_data['send_time'] = 0;
        $sms_send_data['type'] = 2;
        $sms_send_data['sms_cost'] = $total_price;
        $sms_send_data['sms_count'] = $mobile_count;

        $cycle_text['cyctype'] = $cyctype;
        $cycle_text['plan']['month'] = $month;
        $cycle_text['plan']['day'] = $day;
        $cycle_text['plan']['week'] = $week;
        $cycle_text['plan']['hour'] = $hour;
        $cycle_text['plan']['minute'] = $minute;
        
        
        $sms_send_data['cycle_text'] = json_encode($cycle_text);
       
        db('sms_send')->insert($sms_send_data);

        $this->success('短信写入成功!');
    }

    //计算短信费用
    public function calculation(){
        $mobile_count = input('mobile_count');

        $billing = db('billing')->select();

        //计算短信费用
        foreach ($billing as $key => $value) {
            if($value['number'] > $mobile_count){
                $is_bool_price=$value['price'];
                break; 
            }
        }

        //每条价格
        if(isset($is_bool_price)){
            $sms_price = $is_bool_price;
        }else{
            $billing_price = array_column($billing, 'price');
            $sms_price = min($billing_price);
        }

        //总费用
        $total_price = $mobile_count*$sms_price;
        $total_price = round($total_price,2);
        $this->success($total_price);
    }

    //判断运营商
    public function match($mobile){
        if(empty($mobile))return ['bool'=>false,'type'=>0];

        $move = "/^1(3[4-9]|5[012789]|8[78])\d{8}$/";

        $line = "/^1(3[0-2]|5[56]|8[56])\d{8}$/";

        $telecom = "/^((133)|(153)|(173)|(177)|(180)|(181)|(189)|(199))\d{8}$/";

        if(preg_match("/^1[345678]{1}\d{9}$/", $mobile)){
            //移动
            if(preg_match($move, $mobile))$type=2;

            //联通
            if(!isset($type) && preg_match($line, $mobile))$type = 3;

            //电信
            if(!isset($type) && preg_match($telecom, $mobile))$type = 1;
            if(!isset($type))$type=0;

            return ['bool'=>true,'type'=>$type];
        }else{
            return ['bool'=>false,'type'=>0];
        }
    }

    //循环发送
    public function cycle(){


        return $this->fetch();
    }

    //常用短信模板
    public function is_ajax_userd(){
        if(request()->isAjax()){
            $content = input('content');
            $data['content'] = $content;
            $data['uid'] = $this->info['id'];
            $data['cid'] = 0;
            db('sms_list')->insert($data);
            $this->success('修改成功!');
        }

        $where['uid'] = $this->info['id'];
        $list = db("sms_list")
            ->where($where)
            ->order("id desc")
            ->paginate(10)->each(function($item){
                if(!empty($item['cid'])){
                    $name = db('sms_category')->where(['id'=>$item['cid']])->value('name');
                    $item['name'] = $name;
                }else{
                    $item['name'] = '';
                }
                
                return $item;
            });
        $list_count = db('sms_list')->where($where)->count('id');

        $this->assign('list',$list);
        $this->assign('list_count',$list_count);
        return $this->fetch();
    }

    //删除短信模板
    public function del_commonly(){
        $id = input('id');
        db('sms_list')->where(['id'=>$id])->delete();
    }

    //短信模板
    public function commonly_used(){
        $where['uid'] = $this->info['id'];
        $list = db("sms_list")->alias("sm")
            ->join("sms_category sc","sc.id=sm.cid")
            ->where($where)
            ->order("sm.id desc")
            ->field('sm.id as sid,sm.*,sc.*')
            ->paginate(10)->each(function($item){
                $item['url'] = url('Sms/commonly_used_add',array('id'=>$item['sid']));
                return $item;
            });
        $list_count = db('sms_list')->where($where)->count('id');
        $this->assign('list', $list);
        $this->assign('list_count', $list_count);
        return $this->fetch();
    }

    //新增短信
    public function commonly_used_add(){
        $id = input('id');
        if(request()->isPost()){    
            $sms_content = input('sms_content');
            $cid = input('cid');
            if(empty($cid))$this->error('请选择分类!');
            $data['content'] = $sms_content;
            $data['cid'] = $cid;
            $data['uid'] = $this->info['id'];

            if(empty($id)){
                db('sms_list')->insert($data);
            }else{
                db('sms_list')->where(['id'=>$id])->update($data);
            }
            $this->redirect("Sms/commonly_used");
        }

        $sms_category_list = db('sms_category')->order('id desc')->select();
        $sms_list_result = db('sms_list')->where(['id'=>$id])->find();
        $this->assign('sms_category_list',$sms_category_list);
        $this->assign('sms_list_result',$sms_list_result);
        return $this->fetch();
    }

    //txt导入
    public function txt_add(){

        if(request()->isAjax()){
            $file = request()->file("file");
            if($file){
                $info = $file->validate(['ext'=>'txt'])->move('./uploads');
                $path_upload = $info->getSaveName();
                $path_upload = str_replace('\\', '/', $path_upload);
                $path = __ROOT__."/uploads/".$path_upload;
                $path_content = file_get_contents($path);

                if(is_file($path)){
                    //unlink($path);
                }
                $this->success($path_content);
            }
        }


        return $this->fetch();
    }

    //exel
    public function exel_add(){
        if(request()->isAjax()){
            vendor("Excel.PHPExcel");

            $objPHPExcel = new \PHPExcel();

            //获取表单上传文件  
            $file = request()->file('file');

            if($file){
                $info = $file->validate(['ext'=>'xlsx,xls'])->move('./uploads');
                $exclePath = $info->getSaveName();  //获取文件名
                $file_suffix_name = explode('.',$exclePath);
                $file_suffix_name = $file_suffix_name[1];


                $path_upload = str_replace('\\', '/', $exclePath);
                $path = "./uploads/".$path_upload;

               
                if($file_suffix_name == 'xlsx'){
                    $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                }else{  
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                }

                $obj_PHPExcel =$objReader->load($path, $encode = 'utf-8');
                $sheetCount = $obj_PHPExcel->getSheetCount();

                for ($i=0;$i<$sheetCount;$i++) {
                    $startRow = 1;
                    $endRow = 500;
                    $bool = true;

                    do{
                        //excle处理
                        $excel_array = $this->array_excle($path, $file_suffix_name, $startRow, $endRow,$i);

                        foreach ($excel_array as $key => $value) {
                            foreach ($value as $value_text) {
                                $mobile[] = $value_text;
                            }
                        }

                        $startRow += 500;
                        $endRow += 500;
                        
                        $excel_array_count = count($excel_array);
                        if($excel_array_count == 1 && empty($excel_array_count[0][0])){
                            $bool = false;
                        }
                        ob_flush();
                        flush();
                        usleep(1000); //睡会觉，大量读取，冲击挺大
                    }while($bool);

                }
            }
            if(is_file($path)){
                //$path = __ROOT__.$path;
                //unlink($path);
            }
            $mobile = implode(",", $mobile);

            $this->success($mobile);
        }

        return $this->fetch();
    }

    /**
    *excle处理
    */
    function array_excle($file_name, $file_suffix_name, $startRow = 1, $endRow = null,$i){
        ini_set('memory_limit','4072M');    // 临时设置最大内存占用为3G
        set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期

        if($file_suffix_name == 'xlsx'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }else{  
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }

        $objReader->setReadDataOnly(true);

        //如果有指定行数，则设置过滤器
        if ($startRow && $endRow) {
            vendor("Excel.PHPExcels");
            $perf = new \PHPExcels();
            $perf->startRow = $startRow;
            $perf->endRow   = $endRow;
            $objReader->setReadFilter($perf);
        }

        $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8  
        $activeSheet = $obj_PHPExcel->getActiveSheet();
        $total = $activeSheet->getHighestRow(); //总行数

        $excel_array=$obj_PHPExcel->getsheet($i)->toArray();   //转换为数组格式
        return $excel_array;
    }

    //号码库添加
    public function mobile_lib_add(){
        $mobile_lib = db('mobile_lib')->where(['uid'=>$this->info['id']])->select();
        $mobile_lib_string = array_column($mobile_lib, 'mobile');
        $mobile_lib_string = implode(",",$mobile_lib_string);
        $this->success($mobile_lib_string);
    }

    //通讯录添加
    public function address_book_add(){
        $mobile_lib = db('address_book')->where(['uid'=>$this->info['id']])->select();
        $mobile_lib_string = array_column($mobile_lib, 'mobile');
        $mobile_lib_string = implode(",",$mobile_lib_string);
        $this->success($mobile_lib_string);
    }

    //短信发送列表
    public function lists(){
        $where['uid'] = $this->info['id'];
        $where['type'] = '1';
        
        $list = db("sms_send")
            ->where($where)
            ->order("id desc")
            ->paginate(10)->each(function($item){
                $item['creatime'] = date('Y-m-d h:i:s',$item['creatime']);
                if(!empty($item['send_time'])){
                    $item['send_time'] =  date('Y-m-d h:i:s',$item['send_time']);   
                }else{
                    $item['send_time'] =  0;
                }
                return $item;
            });
        $list_count = db('sms_send')->where($where)->count('id');
        $this->assign('list', $list);
        $this->assign('list_count', $list_count);
        return $this->fetch();
    }

    //短信循环发送列表
    public function cycle_list(){
        $where['uid'] = $this->info['id'];
        $where['type'] = '2';
        
        $list = db("sms_send")
            ->where($where)
            ->order("id desc")
            ->paginate(10)->each(function($item){
                $item['creatime'] = date('Y-m-d h:i:s',$item['creatime']);
                if(!empty($item['send_time'])){
                    $item['send_time'] =  date('Y-m-d h:i:s',$item['send_time']);   
                }else{
                    $item['send_time'] =  0;
                }
                $item['cycle_text'] = json_decode($item['cycle_text'],1);

                switch ($item['cycle_text']['cyctype']) {
                    case 'y':
                        $item['cycle_text']['cyctype'] = '年';
                        break;
                    case 'm':
                        $item['cycle_text']['cyctype'] = '年';
                        break;
                    case 'w':
                        $item['cycle_text']['cyctype'] = '周';
                        break;
                    case 'd':
                        $item['cycle_text']['cyctype'] = '日';
                        break;
                    default:
                        # code...
                        break;
                }

                //循环时间查询
                if($item['cycle_send_txt'] != ''){
                    $item['cycle_send_txt'] = json_decode($item['cycle_send_txt'],1);
                    foreach ($item['cycle_send_txt'] as $key => &$value) {
                        $value = date('Y-m-d h:i:s',$value);
                    }
                }

                return $item;
            });
        $list_count = db('sms_send')->where($where)->count('id');
        $this->assign('list', $list);
        $this->assign('list_count', $list_count);
        return $this->fetch();
    }
    //删除
    public function sms_list_del(){
        $id = input('id');
        $where['id'] = $id;

        db('sms_send')->where(['id'=>$id])->delete();
        $this->success('删除成功!');
    }

    //建议
    public function suggest(){

        if(request()->isPost()){
            $content = input('content');
            $uid = $this->info['id'];

            $message = db('message')->where(['uid'=>$uid])->find();

            if(!empty($message)){
                db('message')->where(['uid'=>$uid])->update(['content'=>$content,'time'=>time()]);
            }else{
                db('message')->insert(['content'=>$content,'uid'=>$uid,'time'=>time()]);
            }
        }

        return $this->fetch();
    }

    //号码管理库lise
    public function mobile_lib_list(){
        $keyword=input('keyword');   
        $mobile_type=input('mobile_type');   
        $where['uid'] = $this->info['id'];
        if(!empty($keyword)){
            $where['mobile'] = ['like',["%{$keyword}%"]];
        }

        if(!empty($mobile_type)){
            $where['mobile_type'] = $mobile_type;
        }

        $list = db("mobile_lib")
            ->where($where)
            ->order("id desc")
            ->paginate(10);
        $list_count = db('mobile_lib')->where($where)->count('id');

        $this->assign('keyword',$keyword);
        $this->assign('mobile_type',$mobile_type);
        $this->assign('list', $list);
        $this->assign('list_count', $list_count);
        return $this->fetch();
    }

    //删除号码库
    public function mobile_lib_del(){
        $id = input('id');

        $mobile_lib = db('mobile_lib')->where(['id'=>$id])->find();
        if($mobile_lib['uid'] != $this->info['id'])$this->error('你无权删除别人通讯录!');

        db('mobile_lib')->where(['id'=>$id])->delete();
    }

    //号码管理库
    public function mobile_lib(){

        if(request()->isPost()){
            $mobile_string = input('mobile_string');

            $mobile_array = explode(",",$mobile_string);
            $mobile_count = count($mobile_array);   

            if($mobile_count == 0)$this->error('请输入手机号码!');

            //号码库入库
            $mobile_lib_select = db('mobile_lib')->where(['uid'=>$this->info['id'],'mobile'=>['in',$mobile_array]])->select();
            $mobile_lib_mobile = array_column($mobile_lib_select, 'mobile');
            $mobile_lib_insert = $mobile_array;

            //去除已入库的电话
            if(!empty($mobile_lib_mobile)){
                foreach ($mobile_lib_mobile as $key => $value) {
                    $key = array_search($value,$mobile_lib_insert);
                    unset($mobile_lib_insert[$key]);
                }
            }
            
            if(!empty($mobile_lib_insert)){
                foreach ($mobile_lib_insert as $key => $value) {
                    $data['uid'] = $this->info['id'];
                    $data['mobile'] = $value;
                    $result = $this->match($value);
                    $data['mobile_type'] = $result['type'];
                    $insert_data[] = $data;
                }
                db('mobile_lib')->insertAll($insert_data);
            }

            $this->success("更改成功！",url('Sms/mobile_lib_list'));
        }
        return $this->fetch();
    }
}
